package http

import (
	"encoding/base64"
	"errors"
	"fmt"
	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
	"gorm.io/gorm"
	"mall-portalv2/global"
	"mall-portalv2/internal/server/ctx"
	"mall-portalv2/library/common"
	"net/http"
)

func OrderUpdateOrderHandlerFunc(c *gin.Context) {
	app := ctx.Gin{C: c}

	uidStr, isUid := c.Get("uid")
	if !isUid {
		global.Log.Error("uid不存在")
		app.Response(http.StatusInternalServerError, ctx.StatusInternalServerError, nil)
		return
	}
	UID := common.Str2Int64(fmt.Sprintf("%d", uidStr))

	type RequestBody struct {
		OrderId       int64   `json:"orderId"`
		ReceiverId    int64   `json:"receiverId"`
		FreightAmount float64 `json:"freight_amount" gorm:"freight_amount"` // 运费金额
		Note          string  `json:"note" gorm:"note"`                     // 订单备注
	}

	request := RequestBody{}
	if err := common.BindAndCheck(c, &request); err != nil {
		global.Log.Error("请求参数不正确", zap.Error(err))
		app.Response(http.StatusBadRequest, ctx.StatusBadRequest, err)
		return
	}

	global.Log.Info("映射完成", zap.Any("data", request), zap.Any("UID", UID))

	// TODO: 地址获取
	addressResult, err := svc.QueryUmsMemberReceiveAddressWhereID(c, request.ReceiverId)
	if err != nil {
		global.Log.Error("mysql err", zap.Error(err))
		if err == gorm.ErrRecordNotFound {
			app.Response(http.StatusBadRequest, ctx.StatusBadRequest, "找不到对应的地址记录")
			return
		} else {
			app.Response(http.StatusInternalServerError, ctx.StatusInternalServerError, err)
			return
		}
	}

	if addressResult.MemberId != UID {
		app.Response(http.StatusBadRequest, ctx.StatusBadRequest, errors.New("不是本人的地址"))
		return
	}

	// 订单状态：-1->全部；0->待付款；1->待发货；2->已发货；3->已完成；4->已关闭

	result, err := svc.QueryOmsOrderWhereId(c, request.OrderId, UID)
	if err != nil {
		if err == gorm.ErrRecordNotFound {
			app.Response(http.StatusBadRequest, ctx.StatusBadRequest, err)
			return
		} else {
			global.Log.Error("订单状态查询失败", zap.Error(err))
			app.Response(http.StatusInternalServerError, ctx.StatusInternalServerError, err)
			return
		}
	}

	// TODO: 待付款或者待发货可以修改地址
	if result.Status == 0 || result.Status == 1 {
		// TODO: 修改地址之前需要废弃上一笔订单
		// TODO: 查询上一笔是微信还是支付宝
		queryPayLogsResult, err := svc.QueryPayLogsWhereOrderIdNoWay(c, request.OrderId)
		if err != nil {
			global.Log.Error("mysql err", zap.Error(err))
			app.Response(http.StatusInternalServerError, ctx.StatusInternalServerError, err)
			return
		}

		for _, logs := range queryPayLogsResult {
			if logs.PayType == 1 {
				if err := svc.AliyunClose(result, logs.OrderSn); err != nil {
					global.Log.Error("mysql err", zap.Error(err))
					app.Response(http.StatusInternalServerError, ctx.StatusInternalServerError, err)
					continue
				}
				global.Log.Info("支付宝废弃订单成功")
			} else if logs.PayType == 2 {
				//if err := svc.WechatClose(c, result, logs.OrderSn); err != nil {
				//	global.Log.Error("mysql err", zap.Error(err))
				//	app.Response(http.StatusInternalServerError, ctx.StatusInternalServerError, err)
				//	continue
				//}
				global.Log.Info("微信废弃订单成功")
			}
		}

		payLogsUpdates := make(map[string]interface{})
		payLogsUpdates["close_status"] = 1
		if err := svc.UpdatePayLogsWhereOrderId(c, request.OrderId, payLogsUpdates); err != nil {
			global.Log.Error("mysql err", zap.Error(err))
			app.Response(http.StatusInternalServerError, ctx.StatusInternalServerError, err)
			return
		}
		global.Log.Info("预支付订单修改状态成功")

		orderUpdates := make(map[string]interface{})
		orderUpdates["receiver_id"] = request.ReceiverId
		orderUpdates["receiver_name"] = addressResult.Name
		orderUpdates["receiver_phone"] = addressResult.PhoneNumber
		orderUpdates["receiver_post_code"] = addressResult.PostCode
		orderUpdates["receiver_province"] = addressResult.Province
		orderUpdates["receiver_city"] = addressResult.City
		orderUpdates["receiver_region"] = addressResult.Region
		orderUpdates["receiver_detail_address"] = addressResult.DetailAddress
		orderUpdates["freight_amount"] = request.FreightAmount
		tempNote := base64.StdEncoding.EncodeToString([]byte(request.Note))
		orderUpdates["note"] = tempNote
		if request.FreightAmount > 0 {
			orderUpdates["total_amount"] = result.TotalAmount - result.FreightAmount + request.FreightAmount
			//orderUpdates["pay_amount"] = result.PayAmount
		}
		if err := svc.UpdateOrder(c, request.OrderId, orderUpdates); err != nil {
			global.Log.Error("mysql err", zap.Error(err))
			return
		}
		global.Log.Info("地址更换成功")
		app.Response(http.StatusOK, ctx.OK, nil)
		return
	} else {
		app.Response(http.StatusBadRequest, ctx.StatusBadRequest, nil)
		return
	}
}
